<?php

require_once 'Config.php';
require_once 'alipay-sdk/aop/AopClient.php';
require_once 'alipay-sdk/aop/request/AlipayOfflineMaterialImageUploadRequest.php';

class UploadImage extends Config{
    public function request(){
        $info=[
            'errorCode'=>10001,
            'msg'=>'图片上传失败',
            'data'=>[]
        ];
        if($_FILES){
            if(!isset($_FILES['file'])){
                $info['msg']='请提交图片';
                return json_encode($info);
            }
            $image=$_FILES['file'];
            //图片格式
            preg_match('|\.(\w+)$|', $image['name'], $ext);
            $imageType = strtolower($ext[1]);
            //图片名称
            $imageName = time();
            //图片路径
            $imagePath=$this->uploadImagePath.'/'.$imageName.'.'.$imageType;
            move_uploaded_file($image["tmp_name"], $imagePath);
            //图片二进制内容
            $imageContent='@'.$imagePath;

            $aop = new AopClient ();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $this->app_id;
            $aop->rsaPrivateKey = $this->privateKey;
            $aop->alipayrsaPublicKey=$this->publicKey;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='UTF-8';
            $aop->format='json';
            $request = new AlipayOfflineMaterialImageUploadRequest ();
            $request->setImageType($imageType);
            $request->setImageName($imageName);
            $request->setImageContent($imageContent);
            $result = $aop->execute ($request);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if(!empty($resultCode)&&$resultCode == 10000){
                $info['errorCode']=0;
                $info['msg']='上传成功';
                $info['data']=$result->alipay_offline_material_image_upload_response;
            }else{
                $info['msg']=$result->alipay_offline_material_image_upload_response->msg;
            }
        }
        echo json_encode($info);
    }
}

(new UploadImage())->request();